package cn.com.sina.finance.todolist;

import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;

import cn.com.sina.finance.todolist.base.BaseActivity;
import cn.com.sina.finance.todolist.base.SimpleTabAdapter;
import cn.com.sina.finance.todolist.base.Tab;
import cn.com.sina.finance.todolist.fragment.AddFragment;
import cn.com.sina.finance.todolist.fragment.TodoListFragment;
import cn.com.sina.finance.todolist.fragment.UserFragment;
import cn.com.sina.finance.todolist.view.MainTabId;
import cn.com.sina.finance.todolist.view.MainTabView;

public class MainActivity extends BaseActivity {

    private ViewPager viewPager;
    private TabLayout tabLayout;
    private SimpleTabAdapter tabAdapter;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        viewPager = findViewById(R.id.viewPagerMain);
        tabLayout = findViewById(R.id.tabLayoutMain);

        ArrayList<Tab> tabList = new ArrayList<>();
        tabList.add(new Tab("列表", new TodoListFragment(), MainTabId.TODO_LIST));
        tabList.add(new Tab("添加", new AddFragment(), MainTabId.ADD_TODO));
        tabList.add(new Tab("用户", new UserFragment(), MainTabId.USER));
        tabAdapter = new SimpleTabAdapter(getSupportFragmentManager(), tabList);
        viewPager.setAdapter(tabAdapter);
        viewPager.setOffscreenPageLimit(tabList.size());

        tabLayout.removeAllTabs();
        for (Tab tab : tabList) {
            MainTabView customView = new MainTabView(this);
            customView.init(tab);
            tabLayout.addTab(tabLayout.newTab().setCustomView(customView));
        }

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tabLayout.getTabAt(position).select();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public void initListener() {

    }
}